/**
 *
 * session.c - Copy Queue Library
 *
 * The MIT License
 *
 * Copyright (c) 2008 John Van Enk
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "session.h"

static char libcpqDir[] = ".libcpq";

CPQ_Error_e_t SetDataDir(CPQ_Session_s_t * ses)
{
    int ret = 0;
    int d_len = 0;

    char * home_d;
    char * data_d;

    struct stat s_stat;

    /* Get the user's home directory. */
    if(0 == (home_d = getenv("HOME")))
        return CPQ_ERR_NO_HOME_DIR;

    d_len = sizeof(libcpqDir) + strlen(home_d) + 2; // +2 for '/' and '\0'

    data_d = (char *) calloc(d_len, sizeof(char));
    ret = snprintf(data_d, d_len, "%s/%s", home_d, libcpqDir);

    printf("Using Data Dir: %s\n", data_d);

    /* Check if the ($HOME)/.libcpq directory exists. */
    ret = stat(data_d, &s_stat);

    if(ret) /* Error! */
    {
        if(errno == ENOENT) /* No entity, create it. */
        {
            printf("Creating data directory.\n");
            mkdir(data_d, 0700);
        }
        else /* Something else bad has happened. Tell whoever is behind me to freak out. */
        {
            fprintf(stderr,"Unable to access data directory.\n");
            free(data_d);
            ses->dataDir = 0;

            return CPQ_ERR_BAD_DATA_DIR;
        }
    }
    else
    {
        if(!S_ISDIR(s_stat.st_mode))
        {
           fprintf(stderr,"%s is not a directory.\n", data_d); 
           ses->dataDir = 0;
           free(data_d);

           return CPQ_ERR_BAD_DATA_DIR;
        }
    }

    /* Set the session's data directory to what we just created. */
    ses->dataDir = data_d;

    return CPQ_ERR_OK;
}

